const express = require('express')

const router = express.Router()

const db = require('../db/index')

const { date } = require('../uitls/dateFormat')

//获取电影院
router.get('/cinema', (req, res) => {
    const sql = 'select name from cinema'
    db.query(sql, (err, results) => {
        if (err) return res.cc(err)
        let arr = []
        for (var i in results) {
            let a = Object.values(results[i])
            arr.push(a[0])
        }
        res.send({
            status: 200,
            message: '获取电影成功！',
            data: arr
        })
    })
})

//获取个别影院
router.get('/cinema/:id', (req, res) => {
    const sql = 'select * from cinema where id = ?'
    db.query(sql, req.params.id, function(err, results) {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: "获取影院成功！",
            data: results[0]
        })
    })
})



//获取电影院
router.get('/cinemaAll', (req, res) => {
    const sql = 'select * from cinema'
    db.query(sql, (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: '获取电影成功！',
            data: results
        })
    })
})

//根据名字获取影院
router.get('/cinemaByName', (req, res) => {
    console.log(req.query.name);
    const sql = `select * from cinema where name like '%${req.query.name}%'`
    db.query(sql, (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: '获取电影成功！',
            data: results
        })
    })
})

//删除影院
router.delete('/cinema/:id', (req, res) => {
    const sql = `delete from cinema where id = ${req.params.id}`
    db.query(sql, function(err, results) {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: "删除影院成功！",
        })
    })
})

//添加影院
router.post('/cinema', (req, res) => {
    const cinemaInfo = req.body.cinemaInfo
    const sql = 'insert into cinema set ?'
    db.query(sql, { name: cinemaInfo.name, time: date(cinemaInfo.time) }, (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err.message)
        if (results.affectedRows !== 1) return res.cc('添加失败！')
        res.send({
            status: 200,
            message: '添加成功！',
        })
    })
})


//修改影院信息
router.put('/cinema', (req, res) => {
    const sql = `update cinema set ? where id =${req.body.id}`
    db.query(sql, { name: req.body.name, time: date(req.body.time) }, (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: "修改影院信息成功"
        })
    })
})

module.exports = router